<?php

namespace app\admin\controller\questionnaire\published;

use app\admin\service\TaskService;
use app\BaseController;
use app\model\questionnaire\QuestionnaireTaskModel;
use app\model\questionnaire\QuestionnaireTaskPaperModel;
use app\model\questionnaire\QuestionnaireTaskUserModel;
use app\model\UserModel;
use think\App;

class Index extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 已发布问卷任务
     * @return bool|string
     */
    public function index(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'pageSize|每页显示数' => 'require',
            ]);
            $where = [];
            if (!empty($param['name'])) {
                $where[] = ['name', 'like', '%' . $param['name'] . '%'];
            }
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['start_time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['start_time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['start_time', '<=', $param['end_time']];
                }
            }
            if (isset($param['status']) && strlen($param['status']) > 0) {
                $where[] = ['status', '=', $param['status']];
            }
            if (!empty($param['user_complete_rate'])) {
                $TaskService = new TaskService($this->app);
                $CompletionStatus = $TaskService->CompletionStatus($param['user_complete_rate']);
                $where[] = ['user_complete_rate', 'between', $CompletionStatus['value']];
            }
            if (!empty($param['role_id'])) {
                $UserModel = new UserModel();
                $uid = $UserModel->where('role_id', '=', $param['role_id'])->column('id');
                if (count($uid)) {
                    $where[] = ['uid', 'in', $uid];
                } else {
                    $where[] = ['id', '=', -1];
                }
            }
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $QuestionnaireTaskModel = new QuestionnaireTaskModel();
            $query = $QuestionnaireTaskModel->where($where);
            $data = $query->with([
                'user' => function ($query) {
                    $query->with(['roleName']);
                }
            ])->order('id','desc')->paginate($param['pageSize'])->toArray();
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 任务详情
     * @return bool|string
     */
    public function info(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require|number',
            ]);
            $QuestionnaireTaskModel = new QuestionnaireTaskModel();
            $info = $QuestionnaireTaskModel->with([
                'TaskUser',
                'TaskPaper' => function ($query) {
                    $query->with(['paper']);
                }
            ])->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info = $info->toArray();
            $info['uids'] = array_unique(array_column($info['TaskUser'],'uid'));
            $info['paper'] = $info['TaskPaper'];
            unset($info['TaskUser']);
            unset($info['TaskPaper']);
            $info['result_read_auth'] = explode(',', $info['result_read_auth']);
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 编辑进行中的任务
     * @return bool|string
     */
    public function update2(): bool|string
    {
        $QuestionnaireTaskModel = new QuestionnaireTaskModel();
        $QuestionnaireTaskModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'uids|用户ID' => 'require'
            ]);
            $info = $QuestionnaireTaskModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $QuestionnaireTaskPaperModel = new QuestionnaireTaskPaperModel();
            $paperIds = $QuestionnaireTaskPaperModel->where('task_id', '=', $param['id'])->column('paper_id');
            $QuestionnaireTaskUserModel = new QuestionnaireTaskUserModel();
            $uids = $QuestionnaireTaskUserModel->where('task_id', '=', $param['id'])->column('uid');
            $userData = [];
            foreach ($paperIds as $paper) {
                foreach ($param['uids'] as $uid) {
                    if (!in_array($uid, $uids)) {
                        $userData[] = [
                            'uid' => $uid,
                            'task_id' => $param['id'],
                            'paper_id' => $paper,
                            'time' => time()
                        ];
                    }
                }
            }
            if (!empty($userData)) {
                $QuestionnaireTaskUserModel = new QuestionnaireTaskUserModel();
                $QuestionnaireTaskUserModel->insertAll($userData,200);
            }
            $info->inc('user_num', count($userData));
            $info->is_time = $param['is_time'] ?? 0;
            $info->end_time = $param['end_time'] ?? 0;
            $info->save();
            $QuestionnaireTaskModel->commit();
            return success([], '编辑成功！');
        } catch (\Exception $e) {
            $QuestionnaireTaskModel->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 编辑任务
     * @return bool|string
     */
    public function update(): bool|string
    {
        $QuestionnaireTaskModel = new QuestionnaireTaskModel();
        $QuestionnaireTaskModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'name|任务名称' => 'require',
                'is_time|限时状态' => 'require',
                'result_read_auth|结果查看权限' => 'require',
                'paper|问卷' => 'require',
                'uids|用户' => 'require',
            ]);
            $info = $QuestionnaireTaskModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info->save([
                'is_del' => 1,
                'del_time' => time(),
            ]);
            $param['unit_id'] = $this->userData['unit_id'];
            $param['uid'] = $this->userData['id'];
            $param['result_read_auth'] = implode(',',$param['result_read_auth']);
            $param['time'] = time();
            if (!empty($param['uids']) && !empty($param['paper'])) {
                $userData = [];
                $paperData = [];
                $param['user_num'] = count($param['uids']);
                $param['paper_num'] = count($param['paper']);
                foreach ($param['paper'] as $paper) {
                    $paperData[] = [
                        'paper_id' => $paper['id'],
                        'time' => $param['time']
                    ];
                    foreach ($param['uids'] as $uid) {
                        $userData[] = [
                            'uid' => $uid,
                            'paper_id' => $paper['id'],
                            'time' => $param['time']
                        ];
                    }
                }
                unset($param['uids']);
                unset($param['paper']);
            }
            unset($param['id']);
            $task_id = $QuestionnaireTaskModel->insertGetId($param);
            if (!empty($paperData)) {
                foreach ($paperData as &$v) {
                    $v['task_id'] = $task_id;
                }
                $QuestionnaireTaskPaperModel = new QuestionnaireTaskPaperModel();
                $QuestionnaireTaskPaperModel->insertAll($paperData);
            }
            if (!empty($userData)) {
                foreach ($userData as &$v) {
                    $v['task_id'] = $task_id;
                }
                $QuestionnaireTaskUserModel = new QuestionnaireTaskUserModel();
                $QuestionnaireTaskUserModel->insertAll($userData,200);
            }
            $QuestionnaireTaskModel->commit();
            return success();
        } catch (\Exception $e) {
            $QuestionnaireTaskModel->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 终止任务
     * @return false|string
     */
    public function terminateTask(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $QuestionnaireTaskModel = new QuestionnaireTaskModel();
            $info = $QuestionnaireTaskModel->find($id);
            if (!$info) throw new \Exception('参数错误！');
            if ($info->status == 3) throw new \Exception('任务已终止！');
            $info->status = 3;
            $info->save();
            return success('任务已终止！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 查询任务状态
     * @return bool|string
     */
    public function taskStatus(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $QuestionnaireTaskModel = new QuestionnaireTaskModel();
            if (is_array($id)) {
                $status = $QuestionnaireTaskModel->where('id', 'in', $id)->column('status');
            } else {
                $status = $QuestionnaireTaskModel->where('id', '=', $id)->column('status');
            }
            $status = array_unique($status);
            return success($status);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 任务删除
     * @return bool|string
     */
    public function del(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $QuestionnaireTaskModel = new QuestionnaireTaskModel();
            if (is_array($id)){
                $QuestionnaireTaskModel->where('id', 'in', $id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }else{
                $info = $QuestionnaireTaskModel->find($id);
                if (!$info) throw new \Exception('参数错误！');
                $info->save([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }
}